const axios = require('axios');

const appID = 'wxecc9322469a3f41b';
const appSecret = '7803a7c5261cd59ce2fcc64b7d212b4f';

// 获取 Access Token
async function getAccessToken() {
  try {
    const response = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appSecret}`);
    const accessToken = response.data.access_token;
    console.log('accessToken', accessToken)
    return accessToken;
  } catch (error) {
    console.error('Error getting access token:', error.message);
    return null;
  }
}

// 创建草稿
async function createArticle(accessToken, title, content) {
  try {
    const url = `https://api.weixin.qq.com/cgi-bin/draft/add?access_token=${accessToken}`;
    const data = {
        "articles": [
            {
                "title":title,
                "author": '小黄',
                "digest":DIGEST,
                "content":CONTENT,
                "content_source_url":CONTENT_SOURCE_URL,
                "thumb_media_id":THUMB_MEDIA_ID,
                "need_open_comment":0,
                "only_fans_can_comment":0
            }
            //若新增的是多图文素材，则此处应还有几段articles结构
        ]
    }
    
    const response = await axios.post(url, data);
    console.log('草稿添加', response.data)
    return response.data;
  } catch (error) {
    console.error('Error creating article:', error.message);
    return null;
  }
}

(async () => {
  const accessToken = await getAccessToken();
  
  if (accessToken) {
    const title = '测试测试';
    const content = '第一篇';
    
    const result = await createArticle(accessToken, title, content);
    if (result) {
      console.log('Article published successfully:', result);
    } else {
      console.log('Failed to publish article.');
    }
  }
})();
